package com.github.wui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;


/**
 * 自定义侧滑动Slide组件
 *
 * @author Mr.xie
 */
public class SlideBar extends ViewGroup {
    private static final String TAG = "slideBar";

    private float slideDefaultThreshold = 20;

    private int childHeightMeasureSpec;

    private boolean isScrolled = false;

    public SlideBar(Context context) {
        this(context, null);
    }

    public SlideBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SlideBar);
        this.slideDefaultThreshold = typedArray.getDimension(R.styleable.SlideBar_threshold, 30);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int parentHeight = 0;
        int parentWidth = 0;
        if (getChildCount() == 1) {  // 如果只有一个子布局 则默认撑满
            parentWidth = MeasureSpec.getSize(widthMeasureSpec);
            getChildAt(0).measure(widthMeasureSpec, heightMeasureSpec);
        } else {
            // 父布局宽度 + 子布局宽度之和
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                int childWidth = child.getLayoutParams().width;
                int childHeight = child.getLayoutParams().height;
                if (childWidth == -1) {  // 直接撑满父容器
                    int measureParentWidth = MeasureSpec.getSize(widthMeasureSpec);
                    parentWidth += measureParentWidth;
                    child.measure(widthMeasureSpec, heightMeasureSpec);
                } else {
                    parentWidth += childWidth;
                    int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);

                    if (childHeight == LayoutParams.WRAP_CONTENT) {
                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(childHeight), MeasureSpec.UNSPECIFIED);
                    } else if (childHeight == LayoutParams.MATCH_PARENT) {
                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(parentHeight, MeasureSpec.EXACTLY);
                    } else {
                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
                    }
                    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
                }
            }
        }

        for (int i = 0; i < getChildCount(); i++) {
            int measuredHeight = getChildAt(i).getMeasuredHeight();
            parentHeight = Math.max(parentHeight, measuredHeight);
        }

        // 空出最后一个 留出滑动空间
        setMeasuredDimension(parentWidth -  getChildAt(getChildCount() - 1).getMeasuredWidth(), parentHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int preChildWidth = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            int childMeasuredWidth = child.getMeasuredWidth();
            int childMeasuredHeight = child.getMeasuredHeight();
            child.layout(preChildWidth, 0, preChildWidth + (i + 1) * childMeasuredWidth, getMeasuredHeight());
            preChildWidth += childMeasuredWidth;
        }

    }

    Point startPoint = new Point();

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        isScrolled = true;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startPoint.x = (int) event.getX();
                startPoint.y = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float endX = event.getX();
                float offset = endX - startPoint.x;
                if (endX - startPoint.x < -this.slideDefaultThreshold) {
                    // 设置 子布局的位置
                    View lastChild = getChildAt(getChildCount() - 1);
                    int right = lastChild.getRight();
                    if (right > getMeasuredWidth()) { // 右边越界判断
                        moveChildPosition(offset);
                    }
                }
                if (endX - startPoint.x > this.slideDefaultThreshold) {
                    View firstChild = getChildAt(0);
                    int firstChildLeft = firstChild.getLeft();
                    if (firstChildLeft < 0) { // 左边越界判断
                        moveChildPosition(offset);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                isScrolled = false;
                break;
        }
        invalidate();
        return true;
    }


    /**
     * 移动 子布局的位置
     *
     * @param v 偏移量  负数 表示 向左移动  正数表示向右移动
     */
    private void moveChildPosition(float v) {
        int preChildWidth = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            int childMeasuredWidth = child.getMeasuredWidth();
            int childMeasuredHeight = child.getMeasuredHeight();
            child.animate()
                    .x((int) (preChildWidth + v - slideDefaultThreshold))
                    .setDuration(200);
            child.layout((int) (preChildWidth + v - slideDefaultThreshold), 0, (int) ((preChildWidth + (i + 1) * childMeasuredWidth) + v - slideDefaultThreshold), getMeasuredHeight());
            preChildWidth += childMeasuredWidth;
        }
    }


    /**
     * 返回当前Slider控件是否处于滑动状态
     */
    public boolean isScrolled() {
        return this.isScrolled;
    }
}
